<template>
  <el-form ref="categoryFormRef" :model="categoryForm" :rules="rules" label-width="120px" class="demo-ruleForm"
    :size="formSize" status-icon>
    <el-form-item label="商品类型" prop="name">
      <el-input v-model="categoryForm.name" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(categoryFormRef)">
        添加
      </el-button>
      <el-button @click="resetForm(categoryFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
import api from '@/api'

interface CategoryForm {
  name: string
}

const formSize = ref('default')
const categoryFormRef = ref<FormInstance>()
const categoryForm = reactive<CategoryForm>({
  name: '',
})

const rules = reactive<FormRules<CategoryForm>>({
  name: [
    { required: true, message: '请输入商品类型', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      api.shop.addCategory(categoryForm)
        .then(response => {
          formEl.resetFields()
          ElNotification({
            title: 'Success',
            message: response.data.msg,
            type: 'success',
            duration: 1500
          })
        })
        .catch(error => {
          ElNotification({
            title: 'Error',
            message: error.data.msg,
            type: 'error',
            duration: 1500
          })
        });
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>
  